<template>
  <div class="content">
    <a-form :model="form" :style="{ width: '480px' }" @submit="handleSubmit">
      <a-form-item>
        <div class="title">欢迎登录博客系统</div>
      </a-form-item>

      <a-form-item
        field="name"
        label="用户名"
        :rules="[{ required: true, message: '请输入用户名' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="form.name" placeholder="请输入用户名" allow-clear>
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="pass"
        label="密码"
        :rules="[
          { required: true, message: '请输入密码' },
          { minLength: 5, message: '密码必须大于5位' },
        ]"
        :validate-trigger="['change', 'input']"
      >
        <a-input-password
          v-model="form.pass"
          placeholder="请输入密码"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <!-- 登录按钮,使用loading进行点击保护 -->
        <a-button
          :loading="submitLoading"
          html-type="submit"
          style="width: 100%"
          type="primary"
        >
          {{ loginButtonText }}
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { LOGIN } from "@/api/user";
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import Cookies from "js-cookie";

const router = useRouter();
const submitLoading = ref(false);
const loginButtonText = ref("登录");

const form = reactive({
  name: "",
  pass: "",
  isRead: false,
});

const handleSubmit = async (data) => {
  if (data.errors === undefined) {
    try {
      submitLoading.value = true;
      loginButtonText.value = "登录中";

      let resp = await LOGIN(data.values);

      // 保存cookie
      Cookies.set("username", resp.message.username);

      // 登录成功跳转到后台页面
      // 默认跳转路由名称
      let redirectRouteName = "BackendBlogList";

      // 获取当前url的query参数
      const { redirect, ...otherQuery } = router.currentRoute.value.query;
      let redirectRouteQuery = otherQuery;
      if (redirect) {
        redirectRouteName = redirect;
      }

      // 跳转页面
      router.push({ name: redirectRouteName, query: redirectRouteQuery });
    } catch (error) {
      // 使用反馈组件,提示错误
      Message.error({
        content: `认证失败: ${error.message}`,
        duration: 2000,
      });
    } finally {
      submitLoading.value = false;
      loginButtonText.value = "登录";
    }
  }
};
</script>

<style scoped>
.content {
  display: flex;
  align-content: center;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.title {
  display: flex;
  justify-content: center;
  align-items: center;
  align-content: center;
  width: 100%;
  font-weight: 600;
  font-size: 20px;
}
</style>
